package com.zcxy.fast.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxy.fast.bean.PageQuery;
import com.zcxy.fast.constant.CommonConstant;
import com.zcxy.fast.entity.SysUser;
import com.zcxy.fast.exception.BusinessException;
import com.zcxy.fast.mapper.SysUserMapper;
import com.zcxy.fast.mybatisExtend.BaseServiceImpl;
import com.zcxy.fast.mybatisExtend.LambdaValiteCondition;
import com.zcxy.fast.pojo.LoginVo;
import com.zcxy.fast.service.ISysAttachmentService;
import com.zcxy.fast.service.ISysUserService;
import com.zcxy.fast.utils.BeanCopyUtil;
import com.zcxy.fast.utils.JwtUtil;
import com.zcxy.fast.utils.PasswordUtil;
import com.zcxy.fast.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 平台用户表 服务实现类
 * </p>
 *
 * @author zcc
 * @since 2019-10-11
 */
@Service
public class SysUserServiceImpl extends BaseServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;


    private ISysAttachmentService iSysAttachmentService;

    @Override
    public void addUser(SysUser sysUser) {

        //校验登录名是否唯一，校验手机号是否唯一
        LambdaValiteCondition<SysUser> valiteCondition = LambdaValiteCondition.newInstance(sysUser);
        valiteCondition.addField(SysUser::getLoginName).setErrInfo("登录名已存在，请勿重复添加");
        validFiledExist(valiteCondition);
        //校验手机号是否唯一
        valiteCondition.clear();
        valiteCondition.addField(SysUser::getPhone).setErrInfo("手机号已存在，请勿重复添加");
        validFiledExist(valiteCondition);
        String salt = RandomUtil.randomString(8);
        sysUser.setSalt(salt);
        if (StringUtils.isEmpty(sysUser.getPassword())) {
            sysUser.setPassword("123456");
        }
        String passwordEncode = PasswordUtil.encrypt(sysUser.getPassword(), sysUser.getLoginName(), salt);
        sysUser.setPassword(passwordEncode);
        sysUser.setStatus(CommonConstant.STATUS_NORMAL);
        sysUser.setDelFlag(CommonConstant.DEL_FLAG_1);
        sysUserMapper.insert(sysUser);
        iSysAttachmentService.updateOrAddSysAttachments(sysUser.getAvatar(), sysUser.getAvatarAttachs());
    }

    @Override
    public void updateUser(SysUser t) {

        //校验登录名是否唯一，校验手机号是否唯一
        LambdaValiteCondition<SysUser> valiteCondition = LambdaValiteCondition.newInstance(t);
        valiteCondition.addField(SysUser::getLoginName).setErrInfo("登录名已存在，请勿重复添加");
        valiteCondition.addExcludes(SysUser::getId);
        validFiledExist(valiteCondition);
        //校验手机号是否唯一
        valiteCondition.clear();
        valiteCondition.addField(SysUser::getPhone).setErrInfo("手机号已存在，请勿重复添加");
        valiteCondition.addExcludes(SysUser::getId);
        validFiledExist(valiteCondition);
        sysUserMapper.updateById(t);
        iSysAttachmentService.updateOrAddSysAttachments(t.getAvatar(), t.getAvatarAttachs());

    }

    @Override
    public SysUser getSysUserByLoginName(String loginName) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysUser::getLoginName, loginName);
        SysUser sysUser = baseMapper.selectOne(wrapper);
        return sysUser;
    }

    @Override
    public IPage<SysUser> getList(PageQuery<SysUser> sysUserPageQuery) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        Page<SysUser> page = new Page<SysUser>(sysUserPageQuery.getPageNo(), sysUserPageQuery.getPageSize());
        if (sysUserPageQuery.getT() != null) {
            SysUser sysUser = sysUserPageQuery.getT();
            if (StringUtils.isNotEmpty(sysUser.getLoginName())) {
                queryWrapper.like(SysUser::getLoginName, sysUser.getLoginName());
            }
            if (StringUtils.isNotEmpty(sysUser.getRealName())) {
                queryWrapper.like(SysUser::getRealName, sysUser.getRealName());
            }
            if (StringUtils.isNotEmpty(sysUser.getStatus())) {
                queryWrapper.eq(SysUser::getStatus, sysUser.getStatus());
            }
        }
        IPage<SysUser> pageList = baseMapper.selectPage(page, queryWrapper);

        return pageList;
    }


    @Override
    public LoginVo login(SysUser sysUser) {
        String loginName = sysUser.getLoginName();
        String psw = sysUser.getPassword();
        //验证验证码
        //验证用户名密码
        SysUser sysUserCheck = checkUser(loginName, psw);
        loginName = sysUserCheck.getLoginName();
        //签证
        String jwt = JwtUtil.createTokenByUser(BeanCopyUtil.copyObject(sysUserCheck, com.zcxy.fast.bean.SysUser.class), JwtUtil.SECRET);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken("Bearer " + jwt);
        loginVo.setLoginName(loginName);
        return loginVo;
    }

    public SysUser checkUser(String loginName, String pwd) {
        boolean ret = false;
        SysUser sysUser = new SysUser();
        sysUser.setLoginName(loginName);
        //登录名不区分大小写
        List<SysUser> sysUsers = baseMapper.selectList(new QueryWrapper<>(sysUser));
        if (sysUsers.size() < 1) {
            throw new BusinessException("用户名不存在");
        }
        if ("0".equals(sysUsers.get(0).getStatus())) {
            throw new BusinessException("用户已禁用");
        }
        String passwordEncode = PasswordUtil.encrypt(pwd, sysUsers.get(0).getLoginName(), sysUsers.get(0).getSalt());
        if (!passwordEncode.equals(sysUsers.get(0).getPassword())) {
            throw new BusinessException("密码错误，请重新输入");
        }
        return sysUsers.get(0);
    }

}
